package com.xoa.service.WFE.WFERunner;

import com.alibaba.fastjson.JSONArray;
import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowPrivMapper;
import com.xoa.dao.workflow.FlowRunLogMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.dao.workflow.FlowTypeModelMapper;
import com.xoa.model.department.Department;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.users.UsersService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

import static oracle.net.aso.C05.f;
import static oracle.net.aso.C05.j;

//流程实例基本信息
@Transactional(rollbackFor = Exception.class)
@Service
public class WFEFlowRun {

    @Autowired
    WFEFlowRunMapper wfeFlowRunMapper;

    @Autowired
    FlowPrivMapper flowPrivMapper;

    @Autowired
    WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    WorkMapper workMapper;

    @Autowired
    FlowTypeModelMapper flowTypeModelMapper;

    @Autowired
    WFEFlowTypeModelMapper wfeFlowTypeModelMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    private FlowRunLogMapper flowRunLogMapper;
    @Autowired
    private SysParaMapper sysParaMapper;
    @Resource
    private UsersService usersService;
    @Resource
    private FlowRunPrcsMapper flowRunPrcsMapper;
    //获取runId的最大值
    public int getMaxRunId() {
        String runId = wfeFlowRunMapper.getMaxRunId();
        if (StringUtils.checkNull(runId)) {
            return 0;
        } else {
            return Integer.parseInt(runId);
        }
    }

    //保存流程实例信息
    public void save(FlowRun flowRun) {
        wfeFlowRunMapper.insert(flowRun);
    }

    //查找流程实例
    public FlowRun find(Integer runId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", runId);
        FlowRun f = wfeFlowRunMapper.find(map);
        if (f != null) {
            String endTime = f.getEndTime();
            if (!StringUtils.checkNull(endTime)) {
                if (endTime.contains(".")) {
                    endTime = endTime.substring(0, endTime.length() - 2);
                    f.setEndTime(endTime);
                }
            }
            if (!StringUtils.checkNull(f.getBeginTime())) {
                f.setBeginTime(DateFormat.getStrTime(DateFormat.getTime(f.getBeginTime())));
            }
        }
        return f;
    }

    //查找流程实例
    public FlowRun findAnnex(Integer runId, Integer prcsId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", runId);
        map.put("prcsId", prcsId);
        FlowRun f = wfeFlowRunMapper.findAnnex(map);
        if (f != null) {
            if (!StringUtils.checkNull(f.getBeginTime())) {
                f.setBeginTime(DateFormat.getStrTime(DateFormat.getTime(f.getBeginTime())));
            }
        }
        return f;
    }

    //更新
    public int update(FlowRun flowRun) {
        int a = wfeFlowRunMapper.update(flowRun);
        return a;
    }

    /**
     * 创建作者:   zlf
     * 创建日期:   2018/1/18
     * 方法介绍:   结束时间\工作等级\工作删除状态修改
     * 参数说明:	   @param endTime 结束时间
     * 参数说明:	   @param delFlag  删除状态标志 0或1
     * 参数说明:	   @param workLevel  工作等级
     */
    @Transactional
    public int updateState(Map<String, Object> map) {
        int a = wfeFlowRunMapper.updateState(map);
        return a;
    }

    /**
     * 创建作者:   王禹萌
     * 创建日期:   2018/6/21
     * 方法介绍:   工作批量删除状态修改
     * 参数说明:	   @param endTime 结束时间
     * 参数说明:	   @param delFlag  删除状态标志 0或1
     * 参数说明:	   @param workLevel  工作等级
     */
    @Transactional
    public int batchUpdateState(Map<String, Object> map) {
        int a = wfeFlowRunMapper.batchUpdateState(map);

        return a;
    }


    public int updateAttachment(Map<String, Object> map) {
        int a = wfeFlowRunMapper.updateAttachment(map);
        return a;
    }

    //工作查询
    public BaseWrappers queryFlowRun(Integer state, Integer runId, Integer flowId, String runName, String beginDate, String endDate, String workLevel, String status, String userId,
                                     Integer page, Integer pageSize, boolean useFlag, Users users, String output, HttpServletResponse response, HttpServletRequest request,String wdfqWork  ) {
        //获取库名
        String company = ContextHolder.getConsumerType();
        BaseWrappers baseWrapper = new BaseWrappers();
        Map<String, Object> map = new HashMap<String, Object>();

        //分页插件
    /*    PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
*/
        Integer start = (page - 1) * pageSize;
        map.put("start", start);
        map.put("pageSize", pageSize);

        //指定发起人或者指定办理人传入的userId会有‘，’需要处理
        if (StringUtils.checkNull(userId)) {
            userId = users.getUserId();
        } else if (userId.indexOf(",") > 0) {
            userId = userId.substring(0, userId.length() - 1);
        }

       /* if (!StringUtils.checkNull(userId) && userId.indexOf(",") > 0) {
            userId = userId.substring(0, userId.length() - 1);
        } else {
            if (StringUtils.checkNull(userId) ){
                userId = users.getUserId();
            }
        }*/
        map.put("userId", userId);
        map.put("currentUserId", users.getUserId());
        map.put("currentUid", users.getUid());
        //角色权限为1的默认查询所有流程
        if (1 == users.getUserPriv()) {
            map.put("userPriv", 1);
        }
        //辅助角色为1的默认查询所有流程
        String userPrivOther = users.getUserPrivOther();
        String[] userPrivStr = null;
        if (!StringUtils.checkNull(userPrivOther)) {
            userPrivStr = userPrivOther.split(",");
            if (Arrays.asList(userPrivStr).contains("1")){
                map.put("userPriv", 1);
            }
            /*for (String s : userPrivStr) {
                if ("1".equals(s)) {
                    map.put("userPriv", 1);
                }
            }*/
        }
        //获取当前用户对应查询范围权限的sql
        String myManage = this.getAllQueryPriv(users, "1");
        map.put("myManage", myManage);

        //自己经办runId串
       /* List<Integer> runIds = wfeFlowRunMapper.queryRunId(map);
        map.put("runIds", runIds);*/
        map.put("runId", runId);
        map.put("flowId", flowId);
        map.put("runName", runName);
        map.put("beginDate", beginDate);
        if (StringUtils.checkNull(endDate)) {
            map.put("endDate", DateFormat.getStrDate(new Date()));
        } else {
            map.put("endDate", endDate);
        }
        map.put("workLevel", workLevel);
        map.put("state", state);
        map.put("status", status);
        map.put("wdfqWork", wdfqWork);
        List<Integer> allRunIds = new ArrayList<Integer>();
        Integer count = 0;

        //抛出数据
        List<FlowRunModelPrcs> flowRuns = new ArrayList<FlowRunModelPrcs>();

        try {
            //导出操作
            //2导出所有，1分页导出，此操作用于选择导出数据
            if ("2".equals(output)) {
                allRunIds = wfeFlowRunMapper.queryFlowRunAll(map);
                output = "1";
            }else{
                //所有runId串
                allRunIds = wfeFlowRunMapper.queryFlowRunByPriv(map);
                count = wfeFlowRunMapper.queryFlowRunCount(map);
            }
            //查询所有符合权限的流程
            if (allRunIds.size() > 0) {
                map.put("allRunIds", allRunIds);
                flowRuns = wfeFlowRunMapper.queryFlowRunBylimit(map);
            }
            //Integer count = wfeFlowRunMapper.queryFlowRunCount(map);
            //Integer total = count/pageSize;
            Map<String, Object> paramMap = new HashMap<>();
            for (FlowRunModelPrcs flowRunModelPrcs : flowRuns) {
                if (!"1".equals(output)) {
                    List<Attachment> list = FileUploadUtil.findAtachment(flowRunModelPrcs.getAttachmentId(), flowRunModelPrcs.getAttachmentName(), company);
                    flowRunModelPrcs.setList(list);
                    paramMap.put("flowId", flowRunModelPrcs.getFlowId());
                    paramMap.put("userId", users.getUid());
                    paramMap.put("deptId", users.getDeptId());
                    paramMap.put("roleId", users.getUserPriv());
                    List<Integer> typeList = flowPrivMapper.selPrivByUser(paramMap);//登录人拥有的权限
                    if (typeList.contains(0)) {//全部
                        flowRunModelPrcs.setAll("1");
                    }
                    if (typeList.contains(1)) {//管理
                        flowRunModelPrcs.setManage("1");
                    }
                    if (typeList.contains(2)) {//监控
                        flowRunModelPrcs.setMonitor("1");
                    }
                    if (typeList.contains(3)) {//查询
                        flowRunModelPrcs.setQuery("1");
                    }
                    if (typeList.contains(4)) {//编辑
                        flowRunModelPrcs.setEdit("1");
                    }
                    if (typeList.contains(5)) {//点评
                        flowRunModelPrcs.setComment("1");
                    }
                    if (flowRunModelPrcs.getUserName() == null) {
                        flowRunModelPrcs.setUserName(flowRunModelPrcs.getBeginUser());
                    }
                }
                if (!StringUtils.checkNull(flowRunModelPrcs.getEndTime())) {
                    flowRunModelPrcs.setStatus("已结束");
                } else {
                    flowRunModelPrcs.setStatus("执行中");
                }

                List<FlowRunPrcs> flowRunReacsAllByRunId = wfeFlowRunPrcsMapper.getFlowRunReacsAllByRunIdEnd(String.valueOf(flowRunModelPrcs.getRunId()));
                for (FlowRunPrcs flowRun:flowRunReacsAllByRunId){
                    if (users.getUserId().equals(flowRun.getUserId())){
                        flowRunModelPrcs.setChuan("1");
                    }
                }
            }
            if ("1".equals(output)) {//output==1,则进行导出操作
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("工作流工作查询", 15);
                String[] secondTitles = {"流水号", "流程类型", "工作名称/文号", "流程发起人", "开始时间", "公共附件", "状态"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"runId", "flowName", "runName", "userName", "beginTime", "attachmentName", "status"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, flowRuns, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = response.getOutputStream();

                String filename = "工作流工作查询.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }
            baseWrapper.setFlag(true);
            baseWrapper.setStatus(true);
            baseWrapper.setDatas(flowRuns);
            baseWrapper.setTotal(count);
        } catch (Exception e) {
            e.printStackTrace();
            baseWrapper.setFlag(false);
            baseWrapper.setStatus(false);
            baseWrapper.setMsg(e.getMessage());
        }
        return baseWrapper;
    }


    //表单数据导出
    public void exportFlowData(Integer flowId, String formdata, Users users, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            FlowTypeModel flowTypeModel = flowTypeModelMapper.queryOneObject(flowId);
            String tableName = "flow_data_" + flowId;
            map.put("tableName", tableName);
            //数据库中存储的表单数据
            List<Map<String, Object>> mapList = workMapper.getFlowData(map);
            //表单上所有的字段
            JSONArray json = new JSONArray();
            List<Map<String, Object>> l = json.parseObject(formdata, List.class);
            //设置表头
            int Offset = 2;
            String[] title = new String[l.size() + Offset];
            //设置偏移量
            title[0] = "流水号";
            title[1] = "名称/文号";
            for (int j = 0; j < l.size(); j++) {
                title[j + Offset] = l.get(j).get("value").toString();
            }


            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("工作查询列表信息");
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 12); // 字体高度
            font.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
            font.setFontName("宋体"); // 字体
            font.setBold(true); // 宽度
            font.setItalic(false); // 是否使用斜体
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            style.setFont(font);

            HSSFFont font1 = wb.createFont();
            font1.setFontHeightInPoints((short) 12); // 字体高度
            font1.setColor(HSSFFont.COLOR_NORMAL); // 字体颜色
            font1.setFontName("宋体"); // 字体
            font1.setBold(true); // 宽度
            font1.setItalic(false); // 是否使用斜体
            HSSFCellStyle style1 = wb.createCellStyle();
            style1.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
            style1.setFont(font1);

            HSSFCell cell = row.createCell((short) 0);
            List<String> head = new ArrayList<String>();

            StringBuffer stringBuffer = new StringBuffer();

            for (int i = 0; i < title.length; i++) {
                cell.setCellValue(title[i]);
                cell.setCellStyle(style);
                cell = row.createCell((short) (i + 1));
            }
            // 设置内容
            Map content = new HashMap();
            for (int m = 0; m < mapList.size(); m++) {
                HSSFRow r = sheet.createRow((int) (m + 1));
                //获取表单上所有数据
                Map<String, Object> mapData = mapList.get(m);
                content.put(0, mapData.get("run_id").toString());
                content.put(1, mapData.get("run_name").toString());
                for (int j = 0; j < l.size(); j++) {
                    Map<String, Object> mform = l.get(j);
                    String a = mapData.get(mform.get("key").toString()).toString();
                    content.put(j + Offset, a);
                }
                for (int n = 0; n < content.size(); n++) {
                    cell = r.createCell((short) (n));
                    cell.setCellValue(String.valueOf(content.get(n)));
                    cell.setCellStyle(style1);
                }
            }
            stringBuffer.append(flowTypeModel.getFlowName()).append("全部数据.xls");
            // 设置每一列的宽度
            sheet.setDefaultColumnWidth(15);

            response.setContentType("text/html;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            String fileName = stringBuffer.toString();
            response.setHeader("Content-disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            wb.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public List<FlowRunModelPrcs> toSeniorQuery(Map<String, Object> map) {
        List<FlowRunModelPrcs> list = wfeFlowRunMapper.toSeniorQuery(map);
        return list;
    }

    public List<Integer> queryRunId(Map<String, Object> map) {
        List<Integer> runIds = wfeFlowRunMapper.queryRunId(map);
        return runIds;
    }


    public List<Integer> queryRunIdByFlowId(Map<String, Object> map) {
        List<Integer> runIds = wfeFlowRunMapper.queryRunIdByFlowId(map);
        return runIds;
    }


    /**
     * 获取一个流程的范围部门Id字符串串
     *
     * @param priv
     * @param dept
     * @return
     */
    public String getPrivDeptIds(FlowPrivWithBLOBs priv, Department dept) {
        Set<Department> deptList = new HashSet<Department>();
        String deptIds = "";
        //获取管理权限的管理范围
        String privScope = priv.getPrivScope();
        //获取管理权限的授权类型
        //int privType = priv.getPrivType();
        if ("ALL_DEPT".equals(privScope)) {//如果为全体范围
            deptIds = "0";
            return deptIds;
        } else if ("SELF_DEPT".equals(privScope)) {//本部门,包括下级部门
            //获取本部门和下级部门
            List<Department> deptChildList = departmentMapper.getBydeptNo(dept.getDeptNo());
            deptList.addAll(deptChildList);
        } else if ("SELF_BRANCH".equals(privScope)) {//本部门,不含下属部门
            deptList.add(dept);
        } else if ("SELF_ORG".equals(privScope)) {//本部门,不含下属部门
            deptList.add(dept);
        } else if (!StringUtils.checkNull(privScope)) {//自定义部门
            deptIds = deptIds + privScope;
        }
        Iterator<Department> it = deptList.iterator();
        while (it.hasNext()) {
            Department d = it.next();
            deptIds = deptIds + d.getDeptId() + ",";
        }
        return deptIds;
    }


    /**
     * 工作查询  获取全部流程权限
     *
     * @param users
     * @param queryType 查询类型   0-所有 1-管理  2-监控 3-查询 4-编辑 ；5-点评；
     * @return [{flowTypeId:1 ,postDeptIds:'1,2,3'} , flowTypeId:2 ,postDeptIds:'1,3'}]
     */
    public List getQueryPostDeptsByAllFlow(Users users, Integer queryType) {
        Map<String, Object> m = new HashMap<String, Object>();
        m.put("uid", users.getUid());
        m.put("deptId", users.getDeptId());
        m.put("userPriv", users.getUserPriv());
        m.put("queryType", queryType);
        Department dep = departmentMapper.getDeptById(users.getDeptId());
        List<FlowPrivWithBLOBs> flowPrivList = flowPrivMapper.getFlowPriv(m);//根据监控类型 获取对应的流程
        //获取所有流程和权限部门Id字符串
        List<Map<String, Object>> flowArray = new ArrayList<Map<String, Object>>();
        for (int i = 0, size = flowPrivList.size(); i < size; i++) {
            FlowPrivWithBLOBs flowPriv = flowPrivList.get(i);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("flowId", flowPriv.getFlowId());
            String postDeptIds = this.getPrivDeptIds(flowPriv, dep);
            map.put("postDeptIds", postDeptIds);
            flowArray.add(map);
        }
        return flowArray;
    }


    //根据传入用户信息获取对应工作流查询权限和对应范围的sql,type:1 查询 2监控
    public String getAllQueryPriv(Users users, String type) {
        Map queryData = null;
        // 所有查询权限汇总
        List allPrivList = new ArrayList();

        if ("1".equals(type)) {

            // 查询权限
            List searchPrivList = this.getQueryPostDeptsByAllFlow(
                    users, 3);
            // 编辑权限
            List editPrivList = this.getQueryPostDeptsByAllFlow(
                    users, 4);
            // 点评权限
            List commentPrivList = this.getQueryPostDeptsByAllFlow(
                    users, 5);

            for (int i = 0; i < searchPrivList.size(); i++) {
                queryData = (Map) searchPrivList.get(i);
                allPrivList.add(queryData);
            }
            for (int i = 0; i < editPrivList.size(); i++) {
                queryData = (Map) editPrivList.get(i);
                allPrivList.add(queryData);
            }
            for (int i = 0; i < commentPrivList.size(); i++) {
                queryData = (Map) commentPrivList.get(i);
                allPrivList.add(queryData);
            }
        }
        // 所有权限
        List allList = this.getQueryPostDeptsByAllFlow(
                users, 0);

        // 管理权限
        List managePrivList = this.getQueryPostDeptsByAllFlow(
                users, 1);

        // 监控权限
        List monitorPrivList = this.getQueryPostDeptsByAllFlow(
                users, 2);
        for (int i = 0; i < allList.size(); i++) {
            queryData = (Map) allList.get(i);
            allPrivList.add(queryData);
        }

        for (int i = 0; i < managePrivList.size(); i++) {
            queryData = (Map) managePrivList.get(i);
            allPrivList.add(queryData);
        }

        for (int i = 0; i < monitorPrivList.size(); i++) {
            queryData = (Map) monitorPrivList.get(i);
            allPrivList.add(queryData);
        }

        //我管理的
        StringBuffer myManage = new StringBuffer();
        if (allPrivList.size() != 0) {// 有权限
            for (int i = 0; i < allPrivList.size(); i++) {
                queryData = (Map) allPrivList.get(i);
                if (!String.valueOf(queryData.get("postDeptIds")).equals("")) {// 有权限
                    myManage.append("(fr.FLOW_ID="
                            + queryData.get("flowId"));
                    String postDeptIds = String.valueOf(queryData
                            .get("postDeptIds"));
                    if (!postDeptIds.equals("0")) {// 加入限定部门条件
                        if (postDeptIds.endsWith(",")) {
                            postDeptIds = postDeptIds.substring(0,
                                    postDeptIds.length() - 1);
                        }
                        myManage.append(" and exists (select 1 from department dept where dept.DEPT_ID in ("
                                + postDeptIds + ") and user.DEPT_ID=dept.DEPT_ID)");
                    }
                    myManage.append(")");
                    if (i != allPrivList.size() - 1) {
                        myManage.append(" or ");
                    }
                }
            }
        } else {
            //无任何权限
            myManage.append(" fr.FLOW_ID=0 ");
        }
        return myManage.toString();
    }


    public void exportFlowRunBatch(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) {
        try {
            List<FlowRunModelPrcs> flowRuns = wfeFlowRunMapper.queryFlowRunBylimit(map);
            for (FlowRunModelPrcs flowRunModelPrcs : flowRuns) {
                if (!StringUtils.checkNull(flowRunModelPrcs.getEndTime())) {
                    flowRunModelPrcs.setStatus("已结束");
                } else {
                    flowRunModelPrcs.setStatus("执行中");
                }
            }
            HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("工作流工作查询", 15);
            String[] secondTitles = {"流水号", "流程类型", "工作名称/文号", "流程发起人", "开始时间", "公共附件", "状态"};
            HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
            String[] beanProperty = {"runId", "flowName", "runName", "userName", "beginTime", "attachmentName", "status"};
            HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, flowRuns, beanProperty);
            response.setContentType("text/html;charset=UTF-8");
            OutputStream out = response.getOutputStream();
            String filename = "工作查询导出.xls"; //考虑多语言
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //查找出当前办理人的前十条数据
    public ToJson findFLow(HttpServletRequest request) {
        ToJson<FlowRun> json=new ToJson();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        String runId = request.getParameter("runId");
        String flowId = request.getParameter("flowId");
        String runName = request.getParameter("runName");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String sysPara = sysParaMapper.querySysPara("MYPROJECT").getParaValue();
            if (!StringUtils.checkNull(sysPara) && sysPara.equals("powerchina")) {
                map.put("flag", "0");
            } else {
                map.put("flag", "1");
            }
        } catch (Exception e) {
            map.put("flag", "1");
        }
        map.put("runId", runId);
        map.put("flowId", flowId);
        map.put("runName", runName);
        map.put("userId", user.getUserId());
        List<FlowRun> fLowAndPrcs = wfeFlowRunMapper.findFLowRunPrcs(map);
        List<FlowRun> fLowAndRead = wfeFlowRunMapper.findFLowRunRead(map);
        List<FlowRun> returnData=new ArrayList<>();
        returnData.addAll(fLowAndPrcs);
        returnData.addAll(fLowAndRead);
        Collections.sort(returnData, new Comparator<FlowRun>() {
            @Override
            public int compare(FlowRun o1, FlowRun o2) {
                //降序
                return Integer.valueOf(o2.getRunId()).compareTo(Integer.valueOf(o1.getRunId()));
            }
        });
        List<FlowRun> showList = new ArrayList();
        for (int i = 0; i < returnData.size(); i++) {
            showList.add(returnData.get(i));
            if (i == 10) {
                break;
            }
        }
        json.setObj(showList);
        json.setFlag(0);
        return json;
    }
   //进行保存删除关联流程的runid
    public void saveRelationRunIds(HttpServletRequest request) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        String runId = request.getParameter("runId");
        String flag = request.getParameter("flag");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("runId", runId);
        String RelationRunId=null;
        if(flag.equals("1")){//flag=1是新增  flag=2是删除
            RelationRunId=request.getParameter("RelationRunId")+"|"+users.getUserId();
        }else if(flag.equals("2")){
            RelationRunId=request.getParameter("RelationRunId");
        }
        FlowRun flowRun = wfeFlowRunMapper.find(map);
        String relationRunIds = flowRun.getRelationRunIds();//获取原来的内容
        String relationRunIdsnew="";//新拼接的内容
        if(flag.equals("1")){//flag=1是新增  flag=2是删除
            if(relationRunIds==null||relationRunIds==""){
                relationRunIdsnew=RelationRunId+",";
            }else{
                relationRunIdsnew=relationRunIds+RelationRunId+",";
            }
        }
        if(flag.equals("2")){
            if(relationRunIds!=null&&relationRunIds!=""){
                String[] split = relationRunIds.split(",");
                List<String> list=Arrays.asList(split);
                List<String> arrayList=new ArrayList<String>(list);
                for (String spl:split) {
                    String[] split1 = spl.split("\\|");
                    if(split1[0].equals(RelationRunId)&&split1[1].equals(users.getUserId())){//当前人才能删除关联流程
                        //转换为ArrayLsit调用相关的remove方法
                            arrayList.remove(spl);
                    }
                }
                if(arrayList.size()>0){
                    for (String li:arrayList) {//将去除后的数据拼成串
                        relationRunIdsnew=(relationRunIdsnew+li+",");
                    }
                }else{
                    relationRunIdsnew=null;
                }
            }
        }
        map.put("relationRunIds",relationRunIdsnew);
        wfeFlowRunMapper.updateRelationRunIds(map);
    }
    //查找已关联的流程
    public ToJson findrelationRunIds(HttpServletRequest request) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        ToJson json=new ToJson();
        String[] runIds = request.getParameter("runId").split(",");
        //runId分割，考虑到父流程，若父流程有关联流程，在子流程中要显示父流程所关联的数据
        List<FlowRun> list=new ArrayList();
        for (String runId:runIds) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("runId", runId);
            FlowRun flowRun = wfeFlowRunMapper.find(map);
            //RELATION_RUN_IDS字段存值方式为：1107|admin,1036|admin,
            String relationRunIds = flowRun.getRelationRunIds();//获取原来的内容
            if(relationRunIds!=null&&relationRunIds!=""){
                String[] split = relationRunIds.split(",");
                for (String spl:split) {
                    String[] split1 = spl.split("\\|");
                    FlowRun flowRun1 = this.find(Integer.parseInt(split1[0]));
                    List<String> userIds = flowRunPrcsMapper.selectAllUserByRunId(flowRun1.getRunId());
                    StringBuffer stringBuffer = new StringBuffer();
                    for (String id : userIds) {
                        if(!id.equals(flowRun1.getBeginUser())){//排除发起人
                            stringBuffer.append(id + ",");
                        }
                    }
                    flowRun1.setAllUserName(usersService.getUserNameById(stringBuffer.toString()));
                    if(split1[1].equals(users.getUserId())){//判断前端是否有删除权限
                        flowRun1.setIsDelete("1");
                    }else {
                        flowRun1.setIsDelete("0");
                    }
                    list.add(flowRun1);
                }
            }
        }
        json.setObj(list);
        json.setFlag(0);
        return json;
    }
    //删除意见
    public ToJson deleteOpinion(HttpServletRequest request, FlowRunPrcs flowRunPrcs) {
        ToJson json = new ToJson();
        try{
            String data = request.getParameter("data");
            String timeStamp = request.getParameter("timeStamp");
            List<String> dataList= new ArrayList<>(Arrays.asList(data.split(",")));
            dataList.removeIf(s->!WFEFlowRunInfo.checkNum(s));
            Map<String, Object> dataValue = workMapper.getDataValue(dataList, flowRunPrcs.getRunId(), "flow_data_"+flowRunPrcs.getFlowId());
            Document document = null;
            String dataStr = String.valueOf(dataValue.get(data));
            if(!StringUtils.checkNull(dataStr)){
                //解析html
                document= Jsoup.parse(dataStr);
                try {
                    Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
                    Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
                    FlowRunLog log = new FlowRunLog();
                    log.setRunId(flowRunPrcs.getRunId());//公文主键
                    log.setUserId(user.getUserName());
                    log.setTime(new Date());
                    log.setType(Constant.TYPE21);
                    Elements select = document.select("[time_stamp=" + timeStamp + "]");
                    log.setContent("原意见="+dataStr+"删除的意见"+select);
                    log.setUid(user.getUid());
                    flowRunLogMapper.insertSelective(log);
                }catch (Exception e){
                    e.printStackTrace();
                }

                document.select("[time_stamp="+timeStamp+"]").remove();
                String sql = data+"='"+document.body().children().toString()+"'";
                String tableName = "flow_data_"+flowRunPrcs.getFlowId();
                workMapper.updateDataValue(sql, tableName,flowRunPrcs.getRunId());
                json.setFlag(0);
                json.setMsg("ok");
            }
        }catch (Exception e){
            json.setFlag(1);
            json.setMsg("err");
        }

        return json;
    }

    public int updateViewUser(String runId){
        return wfeFlowRunMapper.updateViewUser(runId);
    }

    //根据flowId查找流程
    public List<FlowRunModelPrcs> findFlowIdRun(Map map){
        String ids =(String) map.get("flowId");
        String sqlType =(String) map.get("sqlType");

        if (StringUtils.checkNull(ids)){
            return new ArrayList();
        }

        if (",".equals(String.valueOf(ids.charAt(ids.length()-1)))){
            map.put("flowId",ids.substring(0,ids.length()-1));
        }

        List<FlowRunModelPrcs> flowIdRun = wfeFlowRunMapper.findFlowIdRun(map);
        for (FlowRunModelPrcs runModel: flowIdRun) {
            if (!StringUtils.checkNull(runModel.getAttachmentId()) && !StringUtils.checkNull(runModel.getAttachmentName())){
                runModel.setList(FileUploadUtil.findAtachment(runModel.getAttachmentId(), runModel.getAttachmentName(), sqlType));
            }
        }
        return flowIdRun;
    }


    public int updatePreSetUser(Integer runId,String preSetUser) {
        int a = wfeFlowRunMapper.updatePreSetUser(runId,preSetUser);
        return a;
    }
}
